package com.jianggy.encryption;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.io.UnsupportedEncodingException;
import java.security.Security;

/**
 *sm3签名工具类
 *@author jianggy
 *@date 2022/3/8
 *@version 1.0
 **/
public class Sm3Util {
    private static final String STRING_ENCODING = "utf-8";

    static {
        /// 注册BouncyCastle,只需要注册一次
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * @param param 需要生成信息摘要的数据
     * @return byte[] 信息摘要的二级制表示
     * @author jianggy
     */
    public static byte[] encryptByte(String param) {
        SM3Digest sm3Digest = new SM3Digest();
        byte[] sourceBytes = new byte[0];
        try {
            sourceBytes = param.getBytes(STRING_ENCODING);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sm3Digest.update(sourceBytes, 0, sourceBytes.length);
        byte[] digestBytes = new byte[sm3Digest.getDigestSize()];
        sm3Digest.doFinal(digestBytes, 0);
        return digestBytes;
    }

    /**
     * @param param 需要生成信息摘要的数据
     * @return String 信息摘要的16进制字符串
     * @author jianggy
     */
    public static String encryptStr(String param) {
        byte[] bytes = encryptByte(param);
        String digestStr = ByteUtils.toHexString(bytes);
        return digestStr;
    }


    /**
     * @param source 源字符串，需要进行验证的字符串
     * @param sm3EncryptStr  sm3 加密后的字符串
     * @return boolean true成功，否则失败
     * @author jianggy
     */
    public static boolean verify(String source, String sm3EncryptStr) {
        String digestStr = encryptStr(source);
        return sm3EncryptStr.equals(digestStr);
    }


}
